package com.zoe.thread.th07_Callable创建线程;

import cn.hutool.core.util.NumberUtil;

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

/**
 * @Author Zoe
 * @Date: 2021/05/04
 * @Description 多线程中：第三种获得多线程的方式：Callable
 * Callable：配合FutureTask使用
 * <p>
 * get()方法一般放在代码块的最后一行调用，防止引起阻塞
 */
class MyThread implements Runnable {
    @Override
    public void run() {
        System.out.println("Runnable");
    }
}

class MyThreadCallable implements Callable {
    @Override
    public Object call() throws Exception {
        try {
            TimeUnit.SECONDS.sleep(4);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Callable接口   " + Thread.currentThread().getName());
        return 1024;
    }


}

public class CallableDemo {
    public static void main(String[] args) throws Exception {
        MyThreadCallable myThreadCallable = new MyThreadCallable();
        FutureTask<Integer> futureTask = new FutureTask<>(myThreadCallable);
        new Thread(futureTask, "A").start();

        int i = 1;
        int b = 1;
        int c = i + b;
        int d = 0;
        // 主线程先计算 1+1;比较简单的运算，然后把一些复杂的运算交给子线程FutureTask来运算，
        System.out.println("main线程计算完成:" + c);

        // 等FutureTask运行完成后，再汇总。
        while (!futureTask.isDone()) {
            d = futureTask.get();
            // 获得Callable线程的返回值
            System.out.println(d);
        }
        System.out.println("线程取消：" + futureTask.isCancelled());
        System.out.println("线程完成：" + futureTask.isDone());
        System.out.println("运行结束,结果汇总:" + NumberUtil.add(d + c));
    }
}
